// Package service internal/service/login_info_service.go
package service

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"gozrd-admin-api/internal/entity/dto"
	"gozrd-admin-api/internal/repository"
	"gozrd-admin-api/pkg/response"
)

// ISysLoginInfoService 登录日志服务接口
type ISysLoginInfoService interface {
	GetSysLoginInfoList(c *gin.Context, username, loginStatus, beginTime, endTime string, pageSize, pageNum int)
	BatchDeleteSysLoginInfo(c *gin.Context, dto dto.DelSysLoginInfoDto)
	DeleteSysLoginInfo(c *gin.Context, dto dto.SysLoginInfoIdDto)
	CleanSysLoginInfo(c *gin.Context)
}

// LoginInfoServiceImpl 登录日志服务实现
type LoginInfoServiceImpl struct {
	loginInfoRepository repository.ILoginInfoRepository
	validator           *validator.Validate
}

// NewLoginInfoService 创建登录日志服务实例
func NewLoginInfoService(loginInfoRepo repository.ILoginInfoRepository) ISysLoginInfoService {
	return &LoginInfoServiceImpl{
		loginInfoRepository: loginInfoRepo,
		validator:           validator.New(),
	}
}

// GetSysLoginInfoList 获取登录日志列表
func (s *LoginInfoServiceImpl) GetSysLoginInfoList(c *gin.Context, username, loginStatus, beginTime, endTime string, pageSize, pageNum int) {
	// 参数校验
	if pageNum < 1 || pageSize < 1 {
		response.Fail(c, response.ErrParams, "分页参数错误")
		return
	}

	// 调用Repository层获取数据
	logs, total, err := s.loginInfoRepository.GetLoginInfoList(pageNum, pageSize, username, loginStatus, beginTime, endTime)
	if err != nil {
		response.Fail(c, response.ErrDatabase, "获取登录日志列表失败："+err.Error())
		return
	}

	// 构建分页结果
	result := map[string]interface{}{
		"total": total,
		"list":  logs,
	}

	response.Success(c, result)
}

// BatchDeleteSysLoginInfo 批量删除登录日志
func (s *LoginInfoServiceImpl) BatchDeleteSysLoginInfo(c *gin.Context, dto dto.DelSysLoginInfoDto) {
	// 验证DTO
	if err := s.validator.Struct(dto); err != nil {
		response.Fail(c, response.ErrParams, err.Error())
		return
	}

	// 调用Repository层
	err := s.loginInfoRepository.BatchDeleteLoginInfo(dto.Ids)
	if err != nil {
		response.Fail(c, response.ErrDatabase, "批量删除登录日志失败："+err.Error())
		return
	}

	response.SuccessWithMessage(c, "批量删除成功", nil)
}

// DeleteSysLoginInfo 删除单条登录日志
func (s *LoginInfoServiceImpl) DeleteSysLoginInfo(c *gin.Context, dto dto.SysLoginInfoIdDto) {
	// 验证DTO
	if err := s.validator.Struct(dto); err != nil {
		response.Fail(c, response.ErrParams, err.Error())
		return
	}

	// 调用Repository层
	err := s.loginInfoRepository.DeleteLoginInfoById(dto.Id)
	if err != nil {
		response.Fail(c, response.ErrDatabase, "删除登录日志失败："+err.Error())
		return
	}

	response.SuccessWithMessage(c, "删除成功", nil)
}

// CleanSysLoginInfo 清空登录日志
func (s *LoginInfoServiceImpl) CleanSysLoginInfo(c *gin.Context) {
	// 调用Repository层
	err := s.loginInfoRepository.CleanLoginInfo()
	if err != nil {
		response.Fail(c, response.ErrDatabase, "清空登录日志失败："+err.Error())
		return
	}

	response.SuccessWithMessage(c, "清空成功", nil)
}
